import { message } from "antd";
import { anyAction } from "../../untils";
const infodata = {
  data: [],
  code: 0,
  userarr: {},
  tabeldata: [],
  copydata: [],
};
const reducer = (state = infodata, { type, payload }: any) => {
  let newState = JSON.parse(JSON.stringify(state));
  const show_Toast = (code: number, msg: any) => {
    switch (code) {
      case 200:
        return message.success(payload.msg);
      case 500:
        return message.error(payload.msg);
      case 201:
        return message.error(payload.msg);
      case 202:
        return message.success(payload.msg);
      default:
        break;
    }
  };
  switch (type) {
    case "GET_LIST":
      newState.data = payload;
      newState.childrenData = payload[0].children;
      return newState;

    case "GET_LIST1":
      newState.tabeldata = payload;
      newState.copydata = payload;
      return newState;
    case "FILTERLIST":
      newState.tabeldata = newState.copydata.filter(
        (item: any, index: number) => {
          return item.state.includes(payload);
        }
      );

      return newState;
    case "LOGIN":
      if (payload.code === 200) {
        // console.log(payload);

        newState.userarr = {
          username: payload.username,
          password: payload.password,
        };
        window.localStorage.setItem("token", payload.token);
      }
      show_Toast(payload.code, payload.msg);
      newState.code = payload.code;
      return newState;
    case "REG":
      if (payload.code === 201) {
        show_Toast(payload.code, payload.msg);
      } else if (payload.code === 202) {
        show_Toast(payload.code, payload.msg);
      }
      return newState;
    case "SHOW_ITEM":
      newState.data.forEach((item: anyAction) => {
        if (item.id === payload.id) {
          item.flag = !item.flag;
        }
      });
      newState.childrenData = payload.children;
      return newState;

    default:
      return newState;
  }
};
export default reducer;
